import { useCallback } from "react";
import { DropResult } from "react-beautiful-dnd";
import {
  useBillboardQueryKey,
  useBillboardsInProject,
  useSearchTasks,
  useTasksQueryKey,
} from "./utils";
import { useReorderBillboard } from "../../hooks/useBillboards";
import { useReorderTasks } from "../../hooks/useTasks";

export const useDragEnd = () => {
  const { data: kanbans } = useBillboardsInProject();
  const kanbansQueryKey = useBillboardQueryKey();
  const tasksQueryKey = useTasksQueryKey();
  const { mutate: reorderKanbans } = useReorderBillboard(kanbansQueryKey);
  const { mutate: reorderTasks } = useReorderTasks(tasksQueryKey);
  const { data: allTasks } = useSearchTasks();

  return useCallback(
    ({ source, destination, type }: DropResult) => {
      if (!destination) return;
      // kanbans
      if (type === "COLUMN") {
        const fromId = kanbans?.[source.index].id;
        const referenceId = kanbans?.[destination.index].id;
        if (
          fromId === undefined ||
          referenceId === undefined ||
          fromId === referenceId
        )
          return;
        const type = source.index > destination.index ? "before" : "after";
        reorderKanbans({ fromId, referenceId, type });
      }
      // tasks
      if (type === "ROW") {
        const fromKanbanId = Number(source.droppableId.split("-")[1]);
        const toKanbanId = Number(destination.droppableId.split("-")[1]);

        const sourceTasks = allTasks?.filter(
          (task) => task.kanbanId === fromKanbanId
        );
        const destinationTasks =
          allTasks?.filter((task) => task.kanbanId === toKanbanId) || [];
        const fromId = sourceTasks?.[source.index].id;

        const referenceId = destinationTasks[destination.index]?.id;
        const sortType =
          fromKanbanId === toKanbanId && source.index < destination.index
            ? "after"
            : "before";

        if (fromId === undefined || fromId === referenceId) return;
        reorderTasks({
          fromId,
          referenceId,
          type: sortType,
          fromKanbanId,
          toKanbanId,
        });
      }
    },
    [kanbans, reorderKanbans, allTasks, reorderTasks]
  );
};
